package config

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"path"
)

// make a copy of this file, rename to settings.go
// then set the correct value for these follow variables
var (
	PublicDirectory        = "/Users/guohua/wswitch/wswitch-server/gserver/src/webserver/public"
	TemplateDirectory      = "/Users/guohua/wswitch/wswitch-server/gserver/src/webserver/templates"
	PublicStorageDirectory = "/home/happy/Documents"
	WebPort                = 3001
	DServerPort            = 18283
	UServerPort            = 4002
	LogFile                = ""
	Daemon                 = ""
	LocalServerId          = 1

	FirmDownloadPath      = "D:\\wxserver\\download\\wifiplug\\firm"
	FirmDownloadUrl       = "http://local.llwant.com:4002/download/wifiplug/firm/1.0/"
	LatestFirmVersionCode = 1
	LatestFirmVersion     = "1.0"

	ApkDownloadPath  = "D:\\wxserver\\download\\wifiplug\\android"
	ApkDownloadUrl   = "http://local.llwant.com:4002/download/wifiplug/android/1.0/cosylink.apk"
	ApkUpdateMessage = "fixed many bugs"
	ApkVersionCode   = 1

	CertificatesDirectory = "/root/wswitch-server/certificates"
	APNSUrl               = "gateway.sandbox.push.apple.com:2195"
	ModulesMinSupport     []ModuleMinSupport
	SentinelEnable = "no"
	ServerId       = "purifiersDevServer"

	RedisDefaultServer = "localhost:6380"
	RedisPasswd        = "123"
	MasterName         = ""
	SentinelAddrs      = []string {"localhost:6380"}
)

type ModuleMinSupport struct {
	ModuleName         string `json:"module_name"`
	ModuleId           int    `json:"module_id"`
	AndroidMinVersion  int    `json:"android_min_version"`
	IosMinVersion      string `json:"ios_min_version"`
	FirmwareMinVersion int    `json:"firmware_min_version"`
}


var (
	loadedCfgFilePath = ""
)

func ReLoadConfigFile() bool {
	if loadedCfgFilePath == "" {
		return false
	}

	return ParseConfigFile(loadedCfgFilePath)
}

func ParseConfigFile(filepath string) bool {
	type Params struct {
		WebRoot                string `json:"web_root"`
		PublicStorageDirectory string `json:"pub_storage"`
		WebPort                int    `json:"web_port"`
		DServerPort            int    `json:"dserver_port"`
		UServerPort            int    `json:"userver_port"`
		LogFile                string `json:"log_file"`
		Daemon                 string `json:"daemon"`

		FirmDownloadPath      string `json:"firm_download_path"`
		FirmDownloadUrl       string `json:"firm_download_url"`
		LatestFirmVersionCode int    `json:"latest_firm_version_code"`
		LatestFirmVersion     string `json:"latest_firm_version"`

		ApkDownloadPath  string `json:"apk_download_path"`
		ApkDownloadUrl   string `json:"apk_download_url"`
		ApkVersionCode   int    `json:"latest_apk_version_code"`
		ApkUpdateMessage string `json:"apk_update_message"`

		CertificatesDirectory string             `json:"certificates_path"`
		APNSUrl               string             `json:"apns_url"`
		ModulesMinSupport     []ModuleMinSupport `json:"modules_min_support"`
		SentinelEnable        string             `json:"sentinel_enable"`

		ServerId string `json:"server_id"`

		RedisPasswd        string   `json:"redis_passwd"`
		MasterName         string   `json:"master_name"`
		RedisDefaultServer string   `json:"redis_default_server"`
		SentinelAddrs      []string `json:"sentinel_addrs"`
	}

	loadedCfgFilePath = filepath

	data, err := ioutil.ReadFile(filepath)
	if err != nil {
		log.Println("read configure file error:", err)
		return false
	}

	var params = &Params{}
	err = json.Unmarshal(data, params)
	if err != nil {
		log.Println("json un-marshal error:", err)
		return false
	}

	log.Println("-------------------Configure params are:-------------------")
	log.Println(params)

	if params.WebRoot != "" {
		PublicDirectory = path.Join(params.WebRoot, "public")
		TemplateDirectory = path.Join(params.WebRoot, "templates")
	}

	if params.PublicStorageDirectory != "" {
		PublicStorageDirectory = params.PublicStorageDirectory
	}

	if params.LogFile != "" {
		LogFile = params.LogFile
	}

	if params.Daemon != "" {
		Daemon = params.Daemon
	}

	// ---------------------
	if params.FirmDownloadPath != "" {
		FirmDownloadPath = params.FirmDownloadPath
	}

	if params.FirmDownloadUrl != "" {
		FirmDownloadUrl = params.FirmDownloadUrl
	}

	if params.LatestFirmVersion != "" {
		LatestFirmVersion = params.LatestFirmVersion
	}

	if params.LatestFirmVersionCode != 0 {
		LatestFirmVersionCode = params.LatestFirmVersionCode
	}

	// ------------------------
	if params.ApkDownloadUrl != "" {
		ApkDownloadUrl = params.ApkDownloadUrl
	}

	if params.ApkUpdateMessage != "" {
		ApkUpdateMessage = params.ApkUpdateMessage
	}

	if params.ApkVersionCode != 0 {
		ApkVersionCode = params.ApkVersionCode
	}

	if params.ApkDownloadPath != "" {
		ApkDownloadPath = params.ApkDownloadPath
	}

	// -----------------------
	if params.CertificatesDirectory != "" {
		CertificatesDirectory = params.CertificatesDirectory
	}

	if params.APNSUrl != "" {
		APNSUrl = params.APNSUrl
	}

	if len(params.ModulesMinSupport) > 0 {
		ModulesMinSupport = params.ModulesMinSupport
	}

	// -------------------------------
	if params.SentinelEnable != "" {
		SentinelEnable = params.SentinelEnable
	}

	if params.ServerId != "" {
		ServerId = params.ServerId
	}

	// -----------------------------------
	if params.RedisDefaultServer != "" {
		RedisDefaultServer = params.RedisDefaultServer
	}

	if params.RedisPasswd != "" {
		RedisPasswd = params.RedisPasswd
	}

	if params.MasterName != "" {
		MasterName = params.MasterName
	}

	if len(params.SentinelAddrs) > 0 {
		SentinelAddrs = params.SentinelAddrs
	}

	return true
}
